package wzh000;

import java.io.BufferedReader;  
import java.io.IOException;
import java.io.InputStreamReader;  
import java.io.PrintWriter;  
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.util.Enumeration;

public class TableClient {
	
	private String localIP;  //client's IP
	private int localPort;        //client's port
	private String serverIP;
	private int serverPort;
	private Socket socket;
	
	TableClient(String serverIP, int serverPort){
		this.serverIP = serverIP;
		this.serverPort = serverPort;
		this.localIP = getIPAddress().toString().split("/")[1];
		this.localPort = 36000;
		try{
			this.socket = new Socket(serverIP, serverPort);
		} catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	public String connect(String msg){
		String inMsg =null;
		try {
			if(this.socket == null){
				this.socket = new Socket(serverIP, serverPort);
			}
			BufferedReader in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));  
	        PrintWriter out = new PrintWriter(this.socket.getOutputStream());  
	        //BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));  
	        
	        out.println(msg);
	        out.flush();
	        
	        inMsg = in.readLine();
	        System.out.println("I received from the table: " + inMsg); 
	        
	        
			
		} catch(IOException ex){
			ex.printStackTrace();
			System.out.println("error");
		}
		
		return inMsg ;
	}
	
	public String getLocalIP(){
		return this.localIP;
	}
	public int getLocalPort(){
		return this.localPort;
	}
	private InetAddress getIPAddress() {
        try {
            for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements();) {
                NetworkInterface networkInterface = interfaces.nextElement();
                if (networkInterface.isLoopback() || networkInterface.isVirtual() || !networkInterface.isUp()) {
                    continue;
                }
                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                if (addresses.hasMoreElements()) {
                    return addresses.nextElement();
                }
            }
        } catch (Exception ex) {
            //logger.debug("Error when getting host ip address: <{}>.", e.getMessage());
        	ex.printStackTrace();
        }
        return null;
    }
	
	

}
